package com.fileoperation;

import android.os.Environment;
import android.os.StatFs;

import com.fileoperation.model.Photo;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016-12-08.
 */

public class FileTools {


    public static final String IMAGE_DIR = "imagedir";
    public static final String DIR_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + IMAGE_DIR;

    public static ArrayList<Photo> getTotalImageList(){
        File file = new File(DIR_PATH);
        if (!file.exists()) return null;
        File[] listFiles = file.listFiles();
        if (listFiles == null || listFiles.length == 0) return null;
        ArrayList<Photo> totalList = new ArrayList<>(listFiles.length);
        for (int i = 0; i < listFiles.length; i++){
            File tempFile = listFiles[i];
            totalList.add(new Photo(tempFile.getName(), DIR_PATH + File.separator, tempFile.length()));
        }
        return totalList;
    }

    public static boolean initDir(){
        File file = new File(FileTools.DIR_PATH);
        if (!file.exists()) {
            boolean imageDir = file.mkdir();
            System.out.println("创建图片文件夹结果：" + imageDir);
            return imageDir;
        }
        return true;
    }


    public static int getTotalFileNum(){
        File file = new File(DIR_PATH);
        if (!file.exists()) return 0;
        File[] listFiles = file.listFiles();
        if (listFiles == null){
            return 0;
        }
        return listFiles.length;
    }

    public static void saveFile(final byte[] bytes, String fileName, Subscriber<String> subscriber){
        File file = new File(DIR_PATH);
        if (file.exists()){
            return;
        }else {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                FileOutputStream fileOutputStream = null;
                BufferedOutputStream bufferedOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(DIR_PATH);
                    bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                    bufferedOutputStream.write(bytes);
                    bufferedOutputStream.flush();
                }catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    // 关闭创建的流对象
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (bufferedOutputStream != null) {
                        try {
                            bufferedOutputStream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                subscriber.onNext(DIR_PATH);
                subscriber.onCompleted();
                subscriber.unsubscribe();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }




    public static long getAvailableSize(String path){
        File file = new File(path);
        if (file.exists()){
            return file.getUsableSpace();
        }else {
            return -1;
        }
    }

    public static long getTotalSize(String path){
        File file = new File(path);
        if (file.exists()){
            return file.getTotalSpace();
        }else {
            return -1;
        }
    }



    /**
     * 查看可用空间是否大于500兆
     * @return
     */
    public static boolean isSpaceEnough(){
        long availableSize = getAvailableSize(DIR_PATH);
        System.out.println("可用存储空间：   " + availableSize);
        return availableSize > (500 * 1024 *1024);
    }

    public static String deskDataStr(){
        long availableSize = getAvailableSize(DIR_PATH);
       return formatSize(availableSize);
    }

    public static String formatSize(long availableSize){
        long kbSize = 1024 ;
        long mbSize = 1024 * 1024;
        long gbSize = 1024 * 1024 * 1024 ;
        if(availableSize < kbSize){
            return "< 1MB";
        }else if(availableSize >= mbSize && availableSize < gbSize){
            return (availableSize / mbSize) + "MB";
        }else {
            return  String.format("%.1f",(availableSize*1.0f) / (gbSize*1.0f) ) + "GB";
        }
    }

    /**
     * 删除图片
     * @param photos
     * @return
     */
    public static Observable<String> deletePhotos(final List<Photo> photos){
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {

                if(photos != null){
                    System.out.println("***********************  calll" + photos.size());

                    for (int i = 0; i < photos.size(); i++){
                        Photo photo = photos.get(i);
                        File file = new File(photo.getPath() + File.separator + photo.getFileName());
                        System.out.println("*****************************");
                        System.out.println(photo.getFileName() + "   " + file.exists());
                        if (file.exists()){
                            boolean delete = file.delete();
                            subscriber.onNext(photo.getFileName());
                        }
                    }
                }
                subscriber.onCompleted();
            }
        });
    }

    public static void deleteAllPhotos(){
        File file = new File(DIR_PATH);
        if (!file.exists()) return ;
        File[] listFiles = file.listFiles();
        if (listFiles == null || listFiles.length == 0) return;
        for (int i = 0; i < listFiles.length; i++){
            File tempFile = listFiles[i];
            tempFile.delete();
        }
    }

}
